package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        // 判断老人是否已经入住(如果已经住入，直接结束流程)，通过身份证号查询老人
        LambdaQueryWrapper<Elder> wrapper=new LambdaQueryWrapper<>();
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        wrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo())
                .in(Elder::getStatus,1,4);//判断老人状态，判断是否已经入住
        //获取老人信息
        Elder elder = elderMapper.selectOne(wrapper);
        //判断老人是否已经入住
        if(ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("该老人已经住入，请勿重复申请住入");
        }
        //如果没有住入，更新床位状态为已入住
        Long bedId = dto.getCheckInConfigDto().getBedId();//床位id
        Bed bed = bedMapper.selectById(bedId);//根据床位id查询床位信息
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //新增或更新老人基本信息（返回值类型待定）
        elder = insertOrUpdateElder(checkInElderDto, bed);
        //新增签约办理
        insertContract(elder,dto.getCheckInContractDto(),dto.getCheckInConfigDto());
        //新增入住信息（同时保存家属信息到remark字段）
        CheckIn checkIn = insertCheckInInfo(elder,bed,dto.getCheckInConfigDto(),dto.getElderFamilyDtoList());
        //新增入住配置
        insertCheckInConfig(checkIn,dto.getCheckInConfigDto());
    }

    /**
     * 查询入住详情
     *
     * @param id
     */
    @Override
    public CheckInDetailVo getElderailById(Long id) {
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.lambdaQuery(CheckInConfig.class).eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo=new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        CheckIn checkIn=checkInMapper.selectCheckInById(id);
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos=JSON.parseArray(remark, ElderFamilyVo.class);

        Elder elder = elderMapper.selectOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getId, checkIn.getElderId()));
        CheckInElderVo checkInElderVo=new CheckInElderVo();
        //计算年龄
        BeanUtils.copyProperties(elder,checkInElderVo);
        //根据出生日期查询生日
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(checkInElderVo.getIdCardNo()));

        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());


        LambdaQueryWrapper<Contract> contractwrapper=new LambdaQueryWrapper<>();
        contractwrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(contractwrapper);
        return new CheckInDetailVo(checkInElderVo, elderFamilyVos, checkInConfigVo, contract);


        //返回数据中加入老人信息（checkInElderVo）
//        CheckInDetailVo checkInDetailVo=new CheckInDetailVo();
//        Elder elder = elderMapper.selectById(id);
//        checkInDetailVo.setCheckInElderVo(elder);
//
//        LambdaQueryWrapper<CheckIn> checkInwrapper=new LambdaQueryWrapper<>();
//        checkInwrapper.eq(CheckIn::getIdCardNo,elder.getIdCardNo());
//        CheckIn checkIn=checkInMapper.selectOne(checkInwrapper);
//        checkInDetailVo.setElderFamilyVoList(checkIn.getRemark());
//
//        LambdaQueryWrapper<CheckInConfig> checkInConfigwrapper=new LambdaQueryWrapper<>();
//        checkInConfigwrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
//        CheckInConfig checkInConfig=checkInConfigMapper.selectOne(checkInConfigwrapper);
//        checkInDetailVo.setCheckInConfigVo(checkInConfig);

//        checkInDetailVo.setContract(contract);
//        return checkInDetailVo;
    }

    /**
     * 新增入住配置信息
     * @param checkIn 入住信息
     * @param checkInConfigDto 入住配置信息
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        //设置入住配置id
        checkInConfig.setCheckInId(checkIn.getId());
        //复制属性
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        //新增入住配置信息
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     *
     * 新增入住信息
     * @param elder 老人信息
     * @param bed   老人入住床位
     * @param checkInConfigDto  入住配置
     * @param elderFamilyDtoList    老人家属列表
     */
    private CheckIn insertCheckInInfo(Elder elder, Bed bed, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
    CheckIn checkIn = new CheckIn();
    //设置老人姓名
    checkIn.setElderName(elder.getName());
    //设置老人id
    checkIn.setElderId(elder.getId());
    //设置老人身份证号
    checkIn.setIdCardNo(elder.getIdCardNo());
    //设置入住开始时间
    checkIn.setStartDate(checkInConfigDto.getStartDate());
    //设置入住结束时间
    checkIn.setEndDate(checkInConfigDto.getEndDate());
    //设置护理等级名称
    checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
    //设置入住床位
    checkIn.setBedNumber(bed.getBedNumber());
    //设置入住老人家属信息
    checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
    //新增入住信息
    checkInMapper.insert(checkIn);
    return checkIn;
    }



    /**
     * 新增签约办理
     * @param elder 老人信息
     * @param checkInContractDto    合同信息
     * @param checkInConfigDto      入住配置信息
     */
    private void insertContract(Elder elder, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto) {
        Contract contract = new Contract();
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        BeanUtils.copyProperties(checkInContractDto,contract);
        //生成一个合同编号
        String contractNumber = CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);

        //设置老人姓名
        contract.setElderName(elder.getName());
        //生成合同开始日期
        contract.setStartDate(checkInConfigDto.getStartDate());
        //生成合同结束日期
        contract.setEndDate(checkInConfigDto.getEndDate());

        //新增签约办理
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     */
    private Elder insertOrUpdateElder(CheckInElderDto dto, Bed bed){
        //判断要新增还是更新老人信息
        String idCardNo=dto.getIdCardNo();
        LambdaQueryWrapper<Elder> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,idCardNo);
        Elder elder = elderMapper.selectOne(wrapper);
        if(ObjectUtil.isNotEmpty(elder)){
            //更新老人信息
            //更新状态为1
            elder.setStatus(1);
            //更新前端传过来的其他基本信息
            BeanUtils.copyProperties(dto,elder);
            //更新床位信息
            elder.setBedId(bed.getId());//床位id
            elder.setBedNumber(bed.getBedNumber());//床位编号
            elderMapper.updateById(elder);//更新老人信息
            return elder;
        }else {
            //新增老人信息
            Elder elderr= new Elder();
            elderr.setStatus(1);
            BeanUtils.copyProperties(dto,elderr);
            elderr.setBedId(bed.getId());
            elderr.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elderr);
            return elderr;
        }
    }
}
